<template>

    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 单品查询
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
       <div class="container" :style="isPc ?'padding:30px': 'padding:10px'">

          <el-row :gutter="0">
            <el-col :md="6" :xs="24" style="margin:3px 0">
                <el-select v-model="query.cat_id" filterable  placeholder="分类" @change="clearMoreParam" clearable  class="handle-select mr10">
                    <el-option v-for = "c in catArr" :key="c.Id" :label="c.Name" :value="c.Id" ></el-option>
                </el-select>
                <el-select v-model="query.brand_id" placeholder="品牌" clearable  class="handle-select">
                    <el-option v-for = "b in brandArr" :key="b.Id" :label="b.Name" :value="b.Id" ></el-option>
                </el-select>
            </el-col>
            <el-col :md="8" :xs="24" style="margin:3px 0">
              <el-input  v-model="query.name" id="bar-code-input"  placeholder="商品名/条形码" @keyup.enter.native="quickSearch" class="handle-input"></el-input>
            </el-col>
<!--                <el-button type="info" icon="el-icon-s-operation" @click="moreSearchOptions">更多选项</el-button>-->
            <el-col :md="8" :xs="24" style="margin:3px 0">
                <el-button type="primary" icon="el-icon-search" @click="handleSearch" style="min-width:100px;margin-right: 20px">搜索</el-button>
<!--                <el-button v-if="isPc" type="danger" icon="el-icon-printer"  @click="beginPrint">打印标签</el-button>-->
                <el-button type="warning" icon="el-icon-circle-plus-outline" @click="addVisible = true;initAddForm()">新增</el-button>
            </el-col>
          </el-row>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                @sort-change="sortChange"
                header-cell-class-name="table-header"
                @selection-change="selectionChange"
            >
                <el-table-column
                        v-if="isPc"
                        type="selection"
                        width="50">
                </el-table-column>
                <el-table-column prop="name" label="商品名"></el-table-column>
                <el-table-column prop="uniq_attr" label="规格"></el-table-column>
                <el-table-column v-if="isPc" prop="brand" label="品牌"></el-table-column>
                <el-table-column v-if="isPc" prop="bar_code" label="商品编码" width="150" align="center"></el-table-column>
<!--                <el-table-column prop="net_price" sortable="custom" label="指导价"></el-table-column>-->
                <el-table-column v-if="isPc" prop="sell_price" sortable="custom" label="售价"></el-table-column>
                <el-table-column v-if="isPc" prop="stock" sortable="custom" label="库存"></el-table-column>
                <el-table-column label="操作" :width="isPc ? '240px': '75px'" align="left">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >修改
                        </el-button>
<!--                        <el-button-->
<!--                                v-if="isPc"-->
<!--                                type="text"-->
<!--                                icon="el-icon-printer"-->
<!--                                @click="printLabel(scope.row)"-->
<!--                        >打印-->
<!--                        </el-button>-->
                        <el-button
                                :style="isPc? 'margin-left:10px': 'margin-left:0'"
                                type="text"
                                icon="el-icon-plus"
                                @click="handleAddStock(scope.row)"
                        >补货
                        </el-button>
<!--                        <el-button-->
<!--                                v-if="isPc"-->
<!--                                type="text"-->
<!--                                icon="el-icon-close"-->
<!--                                @click="handleDelSku(scope.row)"-->
<!--                        >删除-->
<!--                        </el-button>-->
                        <el-button
                            v-if="isPc"
                            type="text"
                            icon="el-icon-s-operation"
                            @click="showStockLog(scope.row.id)"
                        >库存记录
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>


            <div class="pagination">
                <el-pagination
                        background
                        :layout="isPc ? 'prev,next,pager' : 'prev,next'"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="total"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="基本信息" :visible.sync="editVisible" :width="modalWidth" :close-on-click-modal="false">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="商品">
                    <span>{{form.name}}</span>
                </el-form-item>
              <el-form-item label="规格">
                <el-input v-model="form.uniq_attr" placeholder="" class="add-dialog-input"
                ></el-input>
              </el-form-item>
                <el-form-item label="条形码">
                    <el-input v-model="form.bar_code"></el-input>
                </el-form-item>
                <el-form-item label="进价">
                    <el-input v-model="form.in_price"></el-input>
                </el-form-item>
<!--                <el-form-item label="指导价">-->
<!--                    <el-input v-model="form.net_price"></el-input>-->
<!--                </el-form-item>-->
                <el-form-item label="售价">
                    <el-input v-model="form.sell_price"></el-input>
                </el-form-item>
                <el-form-item label="库存">
                    <el-input v-model="form.stock"></el-input>
                </el-form-item>
<!--                <el-form-item label="标签数">-->
<!--                    <el-input v-model="form.label_num"></el-input>-->
<!--                </el-form-item>-->
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="商品入库" :visible.sync="addStockVisible" :width="modalWidth" :close-on-click-modal="false">
            <el-form ref="form" label-width="70px">
                <el-form-item label="补货数量">
                    <el-input v-model="inForm.quantity"></el-input>
                </el-form-item>
            </el-form>
          <el-form ref="form" label-width="70px">
            <el-form-item label="进货价格">
              <el-input v-model="inForm.price"></el-input>
            </el-form-item>
          </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addStockVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveStorage">确 定</el-button>
            </span>
        </el-dialog>

        <!--更多选项弹出框-->
        <el-dialog
                title="搜索参数"
                :visible.sync="searchAttrVisible"
                :width="modalWidth">
            <div v-for="(m, k) in searchOptions">
                <span>{{m.name}}</span>
                <el-select v-model="searchOptions[k].op" clearable  class="handle-select" style="margin: 10px 0 0 20px">
                    <el-option v-for="(o, i) in operatorArr" :key="i"  :label="o"  :value="o"  ></el-option>
                </el-select>
                <el-input v-model="searchOptions[k].val" class="handle-input" style="margin: 10px 0 0 20px" ></el-input>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelMoreSearch">取 消</el-button>
                <el-button type="primary" @click="beginMoreSearch">确 定</el-button>
            </span>
        </el-dialog>

        <!--库存日志-->
        <el-dialog
            title="库存记录"
            :visible.sync="showStockVisible"
            :width="modalWidth"
        >
          <el-table
              :data="stockLogArr"
              stripe
              style="width: 100%;max-height: 600px">
            <el-table-column
                prop="type_str"
                label="类型">
            </el-table-column>
            <el-table-column
                prop="stock"
                label="原库存">
            </el-table-column>
            <el-table-column
                prop="quantity"
                label="变动数量">
            </el-table-column>
            <el-table-column
                prop="price"
                label="价格">
            </el-table-column>
            <el-table-column
                prop="username"
                label="操作人">
            </el-table-column>
            <el-table-column
                prop="create_time"
                label="时间"
                width="160"
            >
            </el-table-column>
          </el-table>
          <span slot="footer" class="dialog-footer">
                  <el-button @click="showStockVisible = false">关 闭</el-button>
              </span>
        </el-dialog>

        <!-- 新增商品框 -->
        <el-dialog title="新增商品" :visible.sync="addVisible"  :width="modalWidth" :close-on-click-modal="false">
            <el-form ref="form" id="add-dialog" :model="addForm" label-width="70px">

                <el-form-item label="商品名">
                    <el-autocomplete
                            v-model="addForm.name"
                            :debounce=0
                            :fetch-suggestions="querySpuName"
                            @select="confirmSelect"
                            class="add-dialog-input"
                    ></el-autocomplete>
                </el-form-item>
                <el-form-item label="分类">
                  <el-select v-model="addForm.cat_id" filterable placeholder="分类" class="add-dialog-input mr10">
                    <el-option v-for = "c in catArr" :key="c.Id" :label="c.Name" :value="c.Id" ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="品牌">
                    <el-select v-model="addForm.brand_id" placeholder="品牌" class="add-dialog-input mr10">
                        <el-option v-for = "b in brandArr" :key="b.Id" :label="b.Name" :value="b.Id" ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="规格">
                  <el-input v-model="addForm.uniq_attr" placeholder="" class="add-dialog-input"
                  ></el-input>
                </el-form-item>
                <el-form-item label="进价">
                    <el-input v-model="addForm.in_price" placeholder="" class="add-dialog-input"
                    ></el-input>
                </el-form-item>
<!--                <el-form-item label="指导价">-->
<!--                    <el-input v-model="addForm.net_price" @blur="setSellPrice" placeholder=""  class="add-dialog-input"-->
<!--                    ></el-input>-->
<!--                </el-form-item>-->
                <el-form-item label="售价">
                    <el-input v-model="addForm.sell_price"  placeholder="" class="add-dialog-input"
                    ></el-input>
                </el-form-item>
                <el-form-item label="库存">
                    <el-input v-model="addForm.stock" placeholder="" class="add-dialog-input"
                    ></el-input>
                </el-form-item>
                <el-form-item label="条形码">
                    <el-input v-model="addForm.bar_code" placeholder="不填则系统默认生成" class="add-dialog-input"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>


    </div>
</template>

<script>
import getLodop from "../../utils/lodop";
export default {
    name: 'goods',
    data() {
        return {
            query: {
                cat_id: '',
                brand_id: '',
                name: '',
                orderBy: '',
                order: '',
                moreParam: [],
                pageIndex: 1,
                pageSize: 10
            },
            modalWidth: '80%',
            isPc: false,
            tableData: [],
            catArr: [],
            brandArr: [],
            searchOptions: [],
            editVisible: false,
            addVisible: false,
            addStockVisible: false,
            setLabelVisible: false,
            searchAttrVisible: false,
            showStockVisible: false,
            editOptions: [],
            form: {},
            addForm: {},
            inForm: {
              quantity: 0,
              in_price: 0,
              sku_id: 0,
            },
            idx: -1,
            id: -1,
            operatorArr: ['=', '<', '>'],
            total: 0,
            selectArr: [],
            stockLogArr: [],
            printTpl: '3',
            app_name: ''
        };
    },
    created() {
        this.http.getPubConf().then(res => {
            this.app_name = res.data.shop_name;
            this.shop_address = res.data.shop_address;
        })
        if (document.body.clientWidth > 768) {
            this.modalWidth = '40%'
            this.isPc = true
        }
        this.getData();
        this.http.getCats().then(res => {
            this.catArr = res.data ? res.data : [];
        });
        this.http.getBrands().then(res => {
            this.brandArr = res.data ? res.data : [];
        });
    },
    activated: function () {
        document.getElementById("bar-code-input").focus();
    },
    mounted: function () {
        document.getElementById("bar-code-input").focus();
    },
    methods: {
        sortChange({ column, prop, order }){
            this.query.orderBy = prop
            this.query.order = order
            this.handleSearch()
        },
        showStockLog(skuId) {
          this.http.stockLog(skuId).then(res => {
            this.stockLogArr =   res.data ? res.data : [];
          });
          this.showStockVisible = true
        },
        initAddForm() {
          this.addForm = {
            name: '',
            net_price: 0,
            in_price: '',
            sell_price: '',
            stock: '',
            bar_code: '',
            uniq_attr: '',
            brand_id: this.brandArr.length > 0 ? parseInt(this.brandArr[0].Id) : '',
            cat_id: this.catArr.length > 0 ? parseInt(this.catArr[0].Id) : '',
          }
        },
        selectionChange(val){
            val.forEach(item => {
                item.label_num = 1
                return item
            })
           this.selectArr = val
        },
        querySpuName(queryString, cb){
            this.http.getSpus({name: queryString}).then(res => {
                let ret = []
                const spus = res.data.list
                if (spus instanceof Array) {
                    for(let i=0; i< spus.length; i++){
                        ret[i] = {}
                        ret[i].value = spus[i].name;
                        ret[i].id = spus[i].id;
                        ret[i].brand_id = spus[i].brand_id;
                        ret[i].cat_id = spus[i].cat_id;
                    }
                }
                cb(ret);
            });
        },
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
        async syncSkuPrice(spuId){
            await this.http.getSpuSkus(spuId).then(res => {
                if(res.data.length >= 2) {
                    let netPrice = ''
                    let inPrice = ''
                    let stock = ''
                    let needFill = false
                    needFill = true
                    res.data.forEach(it => {
                        if(netPrice === '' && inPrice === '') {
                            netPrice = it.net_price
                            inPrice = it.in_price
                        }
                        stock = it.stock
                        if(netPrice !== it.net_price || inPrice !== it.in_price) {
                            needFill = false
                        }
                    })
                    if(needFill) {
                        this.addForm.net_price = netPrice
                        this.addForm.in_price = inPrice
                        this.addForm.stock = stock
                    }
                }
            })
        },
        confirmSelect(item){
            this.addForm.cat_id = parseInt(item.cat_id)
            this.addForm.brand_id = parseInt(item.brand_id)
            this.syncSkuPrice(item.id)
        },
        // 获取 easy-mock 的模拟数据
        getData() {
            this.http.getSkuList(this.query).then(res => {
                this.tableData = res.data.list;
                this.total = res.data.total
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            let moreParam = []
            for (let i = 0; i < this.searchOptions.length; i++) {
                if (this.searchOptions[i].val === '') {
                    continue;
                }
                let _ = Object.assign({}, this.searchOptions[i])
                delete _.name
                moreParam.push(_)
            }
            this.query.more_param = moreParam
            this.getData();
        },
        clearMoreParam(){
            this.searchOptions = []
        },
        quickSearch(){
            this.$set(this.query, 'pageIndex', 1);
            this.http.getSkuList(this.query).then(res => {
                this.tableData = res.data.list;
                this.total = res.data.total
                const pattern = /^\d{11}\d+$/;
                let tableLen = 0
                if(this.tableData instanceof Array) {
                    tableLen = this.tableData.length
                }
                if(tableLen === 0 && pattern.test(this.query.name)){
                    this.addForm.bar_code = this.query.name
                    this.addVisible = true
                    this.query.name = ''
                }
            });
        },
        printLabel(sku){
            let  LODOP = getLodop();
            LODOP.PRINT_INIT("商品标签");
            LODOP.SET_PRINT_PAGESIZE(1, '50mm' , '32mm');
            let b = 0
            LODOP.SET_PRINT_STYLE("FontSize", 10);
            LODOP.SET_PRINT_STYLE("Bold", 1);
            LODOP.ADD_PRINT_TEXT((b + 2) + 'mm', '29mm', '29mm', 40, this.app_name);
            LODOP.SET_PRINT_STYLE("FontSize", 8);
            LODOP.SET_PRINT_STYLE("Bold", 1);
            LODOP.ADD_PRINT_TEXT((b + 3) + 'mm', '3mm', '35mm', 22,  sku.name + sku.uniq_attr);
            LODOP.SET_PRINT_STYLE("FontSize", 10);
            LODOP.SET_PRINT_STYLE("Bold", 0);
            LODOP.ADD_PRINT_TEXT((b + 7) + 'mm', '3mm', '30mm', 22,  "￥" + sku.sell_price);
            LODOP.SET_PRINT_STYLE("FontSize", 6);
            LODOP.ADD_PRINT_TEXT((b + 12) + 'mm', '3mm', '25mm', 22, "右侧扫码更实惠");
            LODOP.ADD_PRINT_TEXT((b + 15) + 'mm', '3mm', '25mm', 22, "周边地区当日达");
            LODOP.ADD_PRINT_BARCODE((b + 19)+ 'mm', '4mm', '28mm', '6mm', "128Auto", sku.bar_code);
            LODOP.SET_PRINT_STYLEA(0,"ShowBarText",0);
            LODOP.SET_PRINT_STYLE("FontSize", 8);
            LODOP.ADD_PRINT_TEXT((b + 26) + 'mm', '2mm', '48mm', 22, "地址:" + this.shop_address);
            LODOP.ADD_PRINT_BARCODE( (b + 6)+ 'mm', '26mm', '21mm', '21mm', "QRCode", 'https://mp.weixin.qq.com/a/~~5nKyiITWqXE~7hUON9C7dNgSChiyRnOANQ~~');
            LODOP.PREVIEW();
        },

        getLength(str) {
            return str.replace(/[\u0391-\uFFE5]/g,"aa").length;   //先把中文替换成两个字节的英文，在计算长度
        },
        //根据cat_id获取选项参数
        moreSearchOptions() {
            if (this.searchOptions.length === 0) {
                this.searchOptions.push({
                    "op" : "<",
                    "name": "售价",
                    "id" : "sku.sell_price",
                    "val" : ""
                })
                this.searchOptions.push({
                    "op" : ">",
                    "name" : "库存",
                    "id" : "sku.stock",
                    "val" : ""
                })
                if(this.query.cat_id > 0) {
                    this.http.reqCatAttr(this.query.cat_id).then(res => {
                        for (let i = 0; i < res.data.length; i++) {
                            if(res.data[i].is_uniq !== '1') {
                                continue
                            }
                            this.searchOptions.push({
                                "op" : "=",
                                "name" : res.data[i].name,
                                "id" : res.data[i].attr_id,
                                "val" : ""
                            })
                        }
                    })
                }
            }
            this.searchAttrVisible = true
        },
        cancelMoreSearch() {
            this.searchAttrVisible = false
            this.searchOptions = []
        },
        beginMoreSearch() {
            this.searchAttrVisible = false
            this.handleSearch()
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                }).catch(() => {});
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.editVisible = true;
        },
        handleAddStock(row) {
            this.form = row;
            this.addStockVisible = true;
        },
        handleDelSku(row) {
            this.http.delSku(row.id)
            this.$message.success('删除成功');
            this.getData();
        },
        handleAttrEdit(row) {
            this.id = row.id
            this.http.reqSkuAttr(row.id).then(res => {
                this.editOptions = res.data;
            })
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.form.stock = parseInt(this.form.stock)
            this.http.editSku(this.form.id, this.form)
            this.$message.success(`修改 ${this.form.name} 成功`);
            this.$set(this.tableData, this.idx, this.form);
        },
        saveStorage() {
          this.addStockVisible = false;
          this.inForm.sku_id = this.form.id
          this.http.addStock(this.inForm)
          this.form.stock = parseInt(this.form.stock) + parseInt(this.inForm.quantity)
          this.$message.success(`入库 ${this.form.name} 成功`);
          this.$set(this.tableData, this.idx, this.form);
        },
        // 保存新增
        saveAdd() {
            this.http.addSku(this.addForm).then(res => {
                if (res.code === 0) {
                    this.addVisible = false;
                    this.$message.success('新增商品' + this.addForm.name + '成功');
                    this.initAddForm()
                } else {
                    this.$message.error(res.msg);
                }
            })
            this.$set(this.query, 'pageIndex', 1);
            this.getData()
        },
    }
};
</script>

<style scoped>
.el-row {
    margin-left: 0;
    margin-bottom: 20px;
    background-color: #fff;
}

.handle-select {
    width: 46%;
}

.add-dialog-input {
    width: 80%;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
